<?php

namespace App\Http\Controllers;

use App\Coach;
use Illuminate\Http\Request;

class CoachController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Coach $model)
    {
        if (!is_null($request->type) && !in_array($request->type, [0, 1, 2]))
            return redirect()->route('coach.index')->withStatus('请选择正确的分类');

        if (is_null($request->search))
            // 按分类查看列表
            $coaches = is_null($request->type)
                ? $model
//                    ->where('status', 1)
//                    ->whereIn('rec_status', [1, 2])
                    ->paginate(15)
                : $model
//                    ->where('status', 1)
                    ->where('rec_status', $request->type)
                    ->paginate(15);
        else
            // 搜索
            $coaches = $model
//                ->where('status', 1)
//                ->whereIn('rec_status', [1, 2])
                ->where('title', 'like', "%{$request->search}%")
                ->orWhere('intro', 'like', "%{$request->search}%")
                ->paginate(15);

        return view('coaches.index', [
            'coaches' => $coaches,
            'countAll' => $model->count(),
            'countStatus0' => $model->where('rec_status', 0)->count(),
            'countStatus1' => $model->where('rec_status', 1)->count(),
            'countStatus2' => $model->where('rec_status', 2)->count(),
        ]);
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param \App\Coach $coach
     * @return \Illuminate\Http\Response
     */
    public function rec(Request $request, Coach $coach)
    {
        $coach->rec_status = $request->get('rec_status');
        $coach->save();
        return response(json_encode((object)[
            'rec_status' => $coach->rec_status,
            'updated_at' => $coach->updated_at->toDateTimeString()
        ]));
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param \App\Coach $coach
     * @return \Illuminate\Http\Response
     */
    public function status(Request $request, Coach $coach)
    {
        $coach->status = $request->get('status');
        $coach->save();
        return response(json_encode((object)[
            'status' => $coach->status,
            'updated_at' => $coach->updated_at->toDateTimeString()
        ]));
    }

}
